//package tech.treec.smartlight.service;
//
//import android.app.Notification;
//import android.app.NotificationChannel;
//import android.app.NotificationManager;
//import android.app.Service;
//import android.content.BroadcastReceiver;
//import android.content.Context;
//import android.content.Intent;
//import android.content.IntentFilter;
//import android.content.SharedPreferences;
//import android.os.Build;
//import android.os.IBinder;
//import android.util.Log;
//
//import androidx.core.app.NotificationCompat;
//import androidx.preference.PreferenceManager;
//
//import com.alibaba.fastjson.JSONArray;
//import com.alibaba.fastjson.JSONObject;
//import com.young.mylib.utils.JsonUtils;
//
//import org.eclipse.paho.android.service.MqttAndroidClient;
//import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
//import org.eclipse.paho.client.mqttv3.MqttCallback;
//import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
//import org.eclipse.paho.client.mqttv3.MqttClient;
//import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
//import org.eclipse.paho.client.mqttv3.MqttException;
//import org.eclipse.paho.client.mqttv3.MqttMessage;
//import org.eclipse.paho.client.mqttv3.MqttPersistenceException;
//import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
//
//import java.text.SimpleDateFormat;
//import java.util.Date;
//import java.util.TimeZone;
//import java.util.Timer;
//import java.util.TimerTask;
//
//import tech.treec.smartlight.R;
//
//public class MQTT2Service extends Service implements MqttCallbackExtended {
//    private static final String TAG = "MQTTMSGService";
//    private Timer serviceTimer = null;
//    private MqttMsgReceiver msgReceiver;
//
//    private static final String CLIENT_ID = "smartLightClientId";
//    private static MqttAndroidClient mqttClient;
//
//
//    public MQTT2Service() {
//    }
//
//    @Override
//    public void onCreate() {
//        super.onCreate();
//        Log.i(TAG, "mqtt 服务建立");
//        // reset status variable to initial state
//        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
//
//        String panelId = prefs.getString("panelId", "588"); // 获取默认值作为备选方案。
//        String topic = "/light/DARMAO000" + panelId + "0000/data/report";
//        msgReceiver = new MqttMsgReceiver();
//        IntentFilter intentFilter = new IntentFilter();
//        intentFilter.addAction(topic);
//        registerReceiver(msgReceiver, intentFilter);
//
//        serviceTimer = new Timer();
//        serviceTimer.schedule(timerTask, 6000, 10000);
//        try {
//            connect();
//        } catch (MqttException e) {
//
//            e.printStackTrace();
//        }
//    }
//
//    @Override
//    public IBinder onBind(Intent intent) {
//        // TODO: Return the communication channel to the service.
//        throw new UnsupportedOperationException("Not yet implemented");
//    }
//
//    @Override
//    public void onStart(final Intent intent, final int startId) {
//        Log.i(TAG, "onStart");
//    }
//
//    @Override
//    public int onStartCommand(final Intent intent, int flags, final int startId) {
//        Log.i(TAG, "onStartCommand");
//        startForeground(1, getNotfication());
//        return START_STICKY;
//    }
//
//    @Override
//    public void onDestroy() {
//        super.onDestroy();
//        try {
//            disconnect();
//        } catch (MqttException e) {
//            e.printStackTrace();
//        }
//        if (msgReceiver != null) {
//            unregisterReceiver(msgReceiver);
//        }
//    }
//
//    private Notification getNotfication() {
//        String channelId = "smart_light_channel";
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//            NotificationChannel channel = new NotificationChannel(channelId, "SMART LIGHT CHANNEL", NotificationManager.IMPORTANCE_DEFAULT);
//            NotificationManager manager = getSystemService(NotificationManager.class);
//            manager.createNotificationChannel(channel);
//        }
//        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channelId)
//                .setContentTitle("Service Running")
//                .setContentText("MyService is running in the foreground")
//                .setSmallIcon(R.drawable.app);
//        return builder.build();
//
//    }
//
//    TimerTask timerTask = new TimerTask() {
//        @Override
//        public void run() {
//            Log.i(TAG, "MQTT is connected?" + mqttClient.isConnected());
//
//            if (mqttClient.isConnected()) {
//                SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
//                String panelId = prefs.getString("panelId", "588"); // 获取默认值作为备选方案。
//                String subTopic = "/light/DARMAO000" + panelId + "0000/data/report";
//
//                try {
//                    heartbeat();
//                    subscribe(subTopic);
//                } catch (MqttException e) {
//                    e.printStackTrace();
//                }
//
//            }
//
//        }
//    };
//
//    @Override
//    public void connectionLost(Throwable cause) {
//        Log.i(TAG, "MQTT CONNECT LOST");
//    }
//
//    @Override
//    public void messageArrived(String topic, MqttMessage message) throws Exception {
//        Log.i(TAG, "MQTT 消息到达：" + topic + ":" + message);
//    }
//
//    @Override
//    public void deliveryComplete(IMqttDeliveryToken token) {
//        Log.i(TAG, "deliveryComplete");
//    }
//
//    public void connect() throws MqttException, MqttPersistenceException {
//
//        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
//
//        String brokerHostName = prefs.getString("mqttUrl", "192.168.119.60"); // 获取默认值作为备选方案。
//        String port = prefs.getString("mqttPort", "1883"); // 获取默认值作为备选方案。
//
//        String panelId = prefs.getString("panelId", "588"); // 获取默认值作为备选方案。
//        String subTopic = "/light/DARMAO000" + panelId + "0000/data/report";
//        String url = "tcp://" + brokerHostName + ":" + port;
//        mqttClient = new MqttAndroidClient(this,url, CLIENT_ID );
//
//
//        mqttClient.setCallback(this);
//        mqttClient.connect();
//    }
//
//    private void heartbeat() throws MqttException {
//        //   Log.i(TAG, "heartbeat:" + isAlreadyConnected());
//        if (mqttClient.isConnected()) {
//            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
//            String panelId = prefs.getString("panelId", "588"); // 获取默认值作为备选方案。
//            String topic = panelId + "/heartbeat";
//            JSONObject json = new JSONObject();
//            json.put("panelId", panelId);
//
//            long ts = System.currentTimeMillis();
//            Date time = new Date(ts);
//            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            format.setTimeZone(TimeZone.getTimeZone("GMT+8"));
//            json.put("time", format.format(time));
////            json["panelId"]=panelId;
//            publish(topic, json.toJSONString());
//        }
//    }
//
//    public static void subscribe(String topic) throws MqttException {
//        mqttClient.subscribe(topic,0);
//        Log.i("Main", topic);
//    }
//
//    public static void publish(String topic, String message) throws MqttException {
//        MqttMessage mqttMessage = new MqttMessage(message.getBytes());
//        mqttClient.publish(topic, mqttMessage);
//    }
//
//    public static void disconnect() throws MqttException {
//        if (mqttClient == null) return;
//        if (mqttClient.isConnected()) {
//            mqttClient.disconnect();
//            mqttClient.close();
//        }
//    }
//
//    @Override
//    public void connectComplete(boolean reconnect, String serverURI) {
//
//    }
//
//    private class MqttMsgReceiver extends BroadcastReceiver {
//
//        @Override
//        public void onReceive(Context context, Intent intent) {
//
//            try {
//                String msg = intent.getStringExtra("msg");
//
//                JSONObject json = JsonUtils.toJSON(msg);
//                JSONArray lightArr = json.getJSONArray("light");
//                Log.i(TAG, "消息到达 lightArr:" + lightArr.toJSONString());
//                JSONArray bodyArr = json.getJSONArray("body");
//                for (Object obj : lightArr) {
//                    JSONObject jo = JsonUtils.toJSON(obj);
//                    Log.i(TAG, jo.getString("deviceId") + ":" + jo.getString("deviceName"));
//                }
//
//            } catch (Exception e) {
//                Log.e(TAG, "MsgReceiver error: " + e.getMessage());
//            }
//        }
//    }
//
//}